<?php
/**
 * 文件http
 */

namespace Xtsb\Cims\File;

use think\facade\Log;

class Http
{
  protected $host = 'https://filesvr.chetell.com';//本地地址

  protected $api = '';

  protected $localHost = 'http://127.0.0.1:1188/127.0.0.1';//文件主机地址


  public function setHost($host = '')
  {
    $request = app('request');

    $this->host = $host;

    if ($request->host() == 'cims.my') {
      $this->host = $this->localHost;
    }

    return $this;
  }

  public function setApi($url = '')
  {
    $this->api = $url;

    return $this;
  }


  public function get($url = '', $code = 'utf-8')
  {
    Log::channel('xtsbfile')->info('数据提交 | ' . $url . '：{data}', ['data' => '获取文件列表']);

    $ch = curl_init();
    $timeout = 30;

    header('User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36');
    curl_setopt($ch, CURLOPT_URL, $this->host . $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);//超时时间：秒

    $result = curl_exec($ch);

    //如果 CURLOPT_HEADER=1 则对返回的结果进行字符串处理
    $curlGetinfo = curl_getinfo($ch);
    curl_close($ch);

    switch ($curlGetinfo['http_code']) {
      case 0:
        $curlGetinfo['error_msg'] = '接口域名错误';
        break;
      case 200:
        $curlGetinfo['error_msg'] = null;
        break;
      case 404:
        $curlGetinfo['error_msg'] = '接口返回404';
        break;
      case 500:
        $curlGetinfo['error_msg'] = '接口返回500';
        break;
      case 502:
        $curlGetinfo['error_msg'] = '无法连接到文件服务器';
        break;
      default:
        break;
    }

    if ($code == 'gb2312') {
      $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换，否则乱码
    }

    if (isset($curlGetinfo['error_msg'])) {
      Log::channel('xtsbfile')->info('返回数据 | ' . $url . '：{data}', ['data' => json_encode($curlGetinfo, JSON_UNESCAPED_UNICODE)]);

      return ['code' => 1, 'msg' => $curlGetinfo['error_msg'], 'data' => []];
    }

    Log::channel('xtsbfile')->info('返回数据 | ' . $url . '：{data}', ['data' => $result]);
    if (json_decode($result)) {
      return json_decode($result, true);
    } else {
      return $result;
    }

    return json_decode($result, true);
  }

  public function post(array $data)
  {

    $postUrl = $this->host . $this->api;
    Log::channel('xtsbfile')->info('数据提交 | ' . $postUrl . '：{data}', ['data' => json_encode($data, JSON_UNESCAPED_UNICODE)]);

    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//表示需要response header
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//        'Content-Type: application/x-www-data-urlencoded; charset=utf-8',
        'Content-Type: application/json; charset=utf-8',
//        'Content-Type: multipart/form-data; charset=utf-8',//文件
      )
    );

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);//请求过期时间
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);//超时时间：秒
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));//这里的http_build_query()函数就是用来处理curl_post传输多维数组的
    //忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $result = curl_exec($ch);//运行curl
    $error = curl_error($ch);

    //如果 CURLOPT_HEADER=1 则对返回的结果进行字符串处理
    $curlGetinfo = curl_getinfo($ch);
    curl_close($ch);

    switch ($curlGetinfo['http_code']) {
      case 0:
        $curlGetinfo['error_msg'] = '接口域名错误';
        break;
      case 200:
        $curlGetinfo['error_msg'] = null;
        break;
      case 404:
        $curlGetinfo['error_msg'] = '接口返回404';
        break;
      case 500:
        $curlGetinfo['error_msg'] = '接口返回500';
        break;
      case 502:
        $curlGetinfo['error_msg'] = '无法连接到文件服务器';
        break;
      default:
        break;
    }

    if (isset($curlGetinfo['error_msg'])) {
      Log::channel('xtsbfile')->info('返回数据 | ' . $postUrl . '：{data}', ['data' => json_encode($curlGetinfo, JSON_UNESCAPED_UNICODE)]);

      return ['code' => 1, 'msg' => $curlGetinfo['error_msg'], 'data' => []];
    }

    Log::channel('xtsbfile')->info('返回数据 | ' . $postUrl . '：{data}', ['data' => $result]);
    if (json_decode($result)) {
      return json_decode($result, true);
    } else {
      return $result;
    }


  }

  /**
   * 暂时不用
   * @param $api
   * @param $filename
   * @param $dirname
   * @return bool|string
   */
  public function postFile($filename, $dirname)
  {

    $postUrl = $this->host . $this->api; //接收方服务器地址与处理方法

//    $file = new \CurlFile(root_path() . 'public' . $filename);
    $file = new \CurlFile($filename);
    $file->setMimeType(mime_content_type($filename));//必须指定文件类型，否则会默认为application/octet-stream，二进制流文件
    $data = [
      'files[]' => $file,//php -v> 5.4
      'file_path' => $dirname,
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $postUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);//表示需要response header
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//        'Content-Type: application/x-www-data-urlencoded; charset=utf-8',
//        'Content-Type: application/json; charset=utf-8',
//        'Content-Type: multipart/form-data; charset=utf-8',//文件
      )
    );

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    //忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $result = curl_exec($ch);//运行curl
    $error = curl_error($ch);

    //如果 CURLOPT_HEADER=1 则对返回的结果进行字符串处理
    $curlGetinfo = curl_getinfo($ch);
    curl_close($ch);

    switch ($curlGetinfo['http_code']) {
      case 0:
        $curlGetinfo['error_msg'] = '接口域名错误';
        break;
      case 200:
        $curlGetinfo['error_msg'] = null;
        break;
      case 404:
        $curlGetinfo['error_msg'] = '接口返回404';
        break;
      case 500:
        $curlGetinfo['error_msg'] = '接口返回500';
        break;
      case 502:
        $curlGetinfo['error_msg'] = '无法连接到文件服务器';
        break;
      default:
        break;
    }

    if (isset($curlGetinfo['error_msg'])) {
      Log::channel('xtsbfile')->info('返回数据 | ' . $postUrl . '：{data}', ['data' => json_encode($curlGetinfo, JSON_UNESCAPED_UNICODE)]);

      return ['code' => 1, 'msg' => $curlGetinfo['error_msg'], 'data' => []];
    }

    if (json_decode($result)) {
      return json_decode($result, true);
    } else {
      return $result;
    }
  }
}
